<?php
/**
 * 归并排序.
 */
function merge_sort($arr) {
    $len = count($arr);
    if ($len <= 1) {
        return $arr;
    }
    $half = ($len>>1) + ($len & 1);
    $arr2d = array_chunk($arr, $half);
    $left = merge_sort($arr2d[0]);
    $right = merge_sort($arr2d[1]);
    while (count($left) && count($right)) {
        if ($left[0] < $right[0]) {
            $reg[] = array_shift($left);
        } else {
            $reg[] = array_shift($right);
        }
    }
    return array_merge($reg, $left, $right);
}

$arr = array(21, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70);
$arr = merge_sort($arr);

//file_put_contents("result.txt", print_r($arr));